<template>
  <div class="login">
    <van-cell-group>
      <van-field
        v-model="username"
        label="用户名"
        placeholder="请输入用户名"
        :error-message="un_msg"
      />
      <van-field
        v-model="password"
        type="password"
        label="密码"
        placeholder="请输入密码"
        :error-message="pw_msg"
      />
    </van-cell-group>
    <van-button style="margin-top: 20px;width: 90%;" size="large" type="primary" @click="login">登录</van-button>
  </div>
</template>

<script>
import request from '@/utils/request';

export default {
  data() {
    return {
      username: '',
      un_msg: '',
      password: '',
      pw_msg: ''
    }
  },
  methods: {
    onAdd() {
      Toast('新增地址');
    },
    login() {
      this.un_msg = '';
      this.pw_msg = '';
      this.username = this.username.trim();
      if (!this.username) {
        this.un_msg = '账号未填写';
        return;
      }
      if (!this.password) {
        this.pw_msg = '密码未填写';
        return;
      }
      request({
        url: '/user/login',
        method: 'post',
        // headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        data: {loginUser: this.username, password: this.password}
      }).then(res => {
        const data = res.data
        if (data.result === 'success') {
          this.$store.dispatch('SetToken', data.token);
          this.$store.dispatch('SetUserInfo', {
            opCode: data.opCOde,
            opName: data.opName,
            departId: data.departId,
            departName: data.departName
          })
          this.$router.replace('/menu');
        } else if(data.code === '1') {
          this.pw_msg = '密码错误';
        } else if(data.code === '2') {
          this.un_msg = '账号不存在';
        } else {
          this.$toast.fail('登录失败!')
        }
      })
    },
    onEdit(item, index) {
      Toast('编辑地址:' + index);
    },
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .login {
    width: 100%;
    position: fixed;
    left: 50%;
    top: 50%;
    -webkit-transform: translate(-50%,-50%);
    -moz-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);
  }
  body {
    background-color: #fafafa;
  }
</style>
